<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2015, http://www.gooraye.net. All Rights Reserved.
// |-----------------------------------------------------------------------------------

namespace Admin\Api;
use Admin\Model\ViewPageItemModel;
use Common\Api\Api;
use Admin\Model\ViewPageModel;
use Shop\Api\ProductApi;
use Shop\Model\ProductGroupModel;

class ViewPageApi extends Api{

    /**
     * 添加
     */
    const ADD = "Admin/ViewPage/add";
    /**
     * 保存
     */
    const SAVE = "Admin/ViewPage/save";
    /**
     * 保存根据ID主键
     */
    const SAVE_BY_ID = "Admin/ViewPage/saveByID";

    /**
     * 删除
     */
    const DELETE = "Admin/ViewPage/delete";

    /**
     * 查询
     */
    const QUERY = "Admin/ViewPage/query";

    /**
     * 查询不分页
     */
    const QUERY_NO_PAGING = "Admin/ViewPage/queryNoPaging";

    /**
     * 查询一条数据
     */
    const GET_INFO = "Admin/ViewPage/getInfo";

    /**
     * 获取page数据,只取第一条记录
     */
    const GET_PAGE_INFO = "Admin/ViewPage/getPageInfo";

    /**
     * 保存page数据
     */
    const SAVE_PAGE_INFO = "Admin/ViewPage/savePageInfo";

    /**
     * 删除page
     */
    const DELETE_PAGE = "Admin/ViewPage/deletePage";

	protected function _init(){
		$this->model = new ViewPageModel();
	}

    /**
     * 获取page数据,只取第一条记录
     */
    public function getPageInfo($map){
        $model = $this->model;
        $result = $model->where($map)->find();
        if($result===false){
            $error = $model->getDbError();
            return $this->apiReturnErr($error);
        }

        //查询pageItem
        if(is_null($result)){
            return $this->apiReturnSuc(null);
        }

        $pageInfo = $result;
        $page_id = $result['id'];
        $item_model = new ViewPageItemModel();
        $map = ['page_id'=>$page_id];
        $result = $item_model->where($map)->order(['display_order'=>'desc'])->select();

        if($result===false){
            $error = $model->getDbError();
            return $this->apiReturnErr($error);
        }

        foreach($result as &$val){
            $data = json_decode($val['data'],true);
            foreach($data['banners'] as &$v){
                if(isset($v['product_home'])){
                    $v['product_home']['product_info'] = $this->queryProductInfo($v['product_home']['product_ids']);
                }
            }

            $val['data'] = json_encode($data);
        }

        $pageInfo['item_data'] = $result;

        return $this->apiReturnSuc($pageInfo);

    }

    private function queryProductInfo($ids){
        if(empty($ids))return [];
        $map['id'] = ['in',$ids];
        $field = ['product_id','name','img','price'];
        $page = ['curpage'=>0,'size'=>100];
        $result = apiCall(ProductApi::QUERY_WITH_COUNT,[$map,$page,false,false,$field]);
        if($result['status']){
            $list = $result['info']['list'];
            $data = [];
            foreach($ids as $val){
                foreach($list as $val2){
                    if($val2['product_id']==$val){
                        $data[] = $val2;
                    }
                }
            }
            return $data;
        }else{
            return [];
        }

    }

    /**
     * 保存page数据,
     */
	public function savePageInfo($pageInfo){
        /*let pageData = [
            {
                block_id : 1,
                item_name: '首页四格'
                banners: [
                    {key:1 ,id:0, name:'保税区',width:150, height:150,
                        group_product_list :{
                        p_ids: [],
                            sku: {
                        }
                        }
                    },
                    {key:2, id:0, name:'搭配购',width:150, height:150,
                        group_product_list :{
                        p_ids: [],
                            sku: {
                        }
                        }
                    },
                    {key:3, id:0, name:'特卖汇',width:150, height:150,
                        group_product_list :{
                        p_ids: [],
                            sku: {
                        }
                        }
                    },
                    {key:4, id:0, name:'限量购',width:150, height:150,
                        group_product_list :{
                        p_ids: [],
                            sku: {
                        }
                        }
                    }
                ]
            }
        ];*/

        $page_data = $pageInfo['page_data'];
        $page_id = $pageInfo['page_id'];

        $map = ['id'=>$page_id];
        $model = $this->model;
        $result = $model->where($map)->find();
        if($result===false){
            $error = $model->getDbError();
            return $this->apiReturnErr($error);
        }

        //查询pageItem
        if(is_null($result)){
            return $this->apiReturnErr('保存失败,指定page不存在');
        }

        $item_model = new ViewPageItemModel();
        $item_model->startTrans();
        $flag = true;

        foreach($page_data as $val){

            $data = [
                'page_id' => $page_id,
                'item_name' => $val['block_name'],
                'dt_item_type' => $val['block_type'],
                'data' => json_encode($val)
            ];
            $map = [
                'id'=>$val['block_id'],
                'page_id' => $page_id
            ];

            $result = $item_model->where($map)->save($data);
            if($result===false){
                $flag = false;
                break;
            }else{
                $result = $item_model->where($map)->count();
                if($result==0){
                    $result = $item_model->add($data);
                    if($result===false){
                        $flag = false;
                        break;
                    }
                }
            }

        }

        if($flag){

            //根据页面建立商品分组('页面分组+pageItem_id+banner_index')
            $result = $this->_createGroup($page_id);
            if($result['status']){
                $item_model->commit();
                return $this->apiReturnSuc('保存成功');
            }else{
                $item_model->rollback();
                return $this->apiReturnErr($result['info']);
            }

        }else{
            $item_model->rollback();
            return $this->apiReturnErr('保存失败');
        }

    }

    /**
     * 根据页面建立商品分组('页面分组+pageItem_id+banner_index')
     */
    public function _createGroup($page_id){
        $result = $this->getPageInfo(['id'=>$page_id]);
        if(!$result['status']){
            return $this->apiReturnErr($result['info']);
        }
        $page_info = $result['info'];
        if(is_null($page_info)){
            return $this->apiReturnErr('页面item不存在');
        }

        $item_data = $page_info['item_data'];

        //查找页面商品分组 data id;
        $map = [
            'name' => '页面商品分组',
            'level' => 0
        ];
        $result = apiCall(DatatreeApi::GET_INFO,[$map]);
        if($result['status']){
            if(is_null($result['info'])){
                return $this->apiReturnErr('创建失败，页面分组商品dataTree不存在');
            }
            $dt_id = $result['info']['id'];
        }else{
            return $this->apiReturnErr($result['info']);
        }

        $model = $this->model;
        $model->startTrans();
        $flag = true;
        foreach($item_data as $val){
            if(!$flag) break;
            $data = json_decode($val['data'],true);
            $banners = $data['banners'];
            foreach($banners as $key=>$val2){
                if(isset($val2['group_product_list']['sku'])){
                    $group_name = "页面商品分组.$page_id.".$val['id'].".$key";
                    //创建数据字典
                    $map = [
                        'name' => $group_name,
                        'parentid' => $dt_id,
                        'level' => 1
                    ];
                    $result = apiCall(DatatreeApi::GET_INFO,[$map]);
                    if($result['status']){
                        if(is_null($result['info'])){
                            //创建对应的数据字典
                            $entity = [
                                'name' => $group_name,
                                'parentid' => $dt_id,
                                'level' => 1,
                                'parents' => "0,$dt_id"
                            ];
                            $result = apiCall(DatatreeApi::ADD,[$entity]);
                            if($result['status']){
                                $g_id = $result['info'];
                            }else{
                                $flag = false;
                                break;
                            }
                        }else{
                            $g_id = $result['info']['id'];
                        }
                        $sku = $val2['group_product_list']['sku'];
                        $result = $this->saveGroupSku($sku, $g_id);
                        if(!$result['status']){
                            $flag = false;
                            break;
                        }
                    }else{
                        $flag = false;
                        break;
                    }

                }
            }
        }

        if($flag){
            $model->commit();
            return $this->apiReturnSuc('保存成功');
        }else{
            $error = $model->getDbError();
            $model->rollback();
            return $this->apiReturnErr($error);
        }
    }

    /**
     * 根据页面删除group
     */
    public function deleteGroup(){
        //TODO:根据页面删除group
    }

    public function saveGroupSku($sku_list,$g_id){
        $model = new ProductGroupModel();
        $model->startTrans();
        $flag = true;
        if(count($sku_list)==0){
            return $this->apiReturnSuc('保存成功');
        }
        foreach($sku_list as $key=>$val){
            if($val==null){
                continue;
            }
            $result = $model->where(['p_id'=>$key,'g_id'=>$g_id])->delete();
            if($result===false){
                $flag = false;
                break;
            }
            $dataList = [];
            foreach($val as $v2){
                $dataList[] = [
                    'sku_id'=>$v2['sku_id'],
                    'g_id'=>$g_id,
                    'p_id'=>$key,
                    'start_time'=>$v2['start_time'],
                    'end_time'=>$v2['end_time'],
                    'price'=>$v2['price'],
                    'display_order'=>$v2['display_order']
                ];
            }
            $result = $model->addAll($dataList);
            if($result===false){
                $flag = false;
                break;
            }
        }
        if($flag){
            $model->commit();
            return $this->apiReturnSuc('保存成功');
        }else{
            $error = $model->getDbError();
            $model->rollback();
            return $this->apiReturnErr($error);
        }
    }


    /**
     * 删除page,只删除第一条
     */
    public function deletePage($map){

        $model = $this->model;
        $flag = true;
        $model->startTrans();

        $result = $model->where($map)->find();
        if($result===false){
            $flag=false;
        }else{
            if(!is_null($result)){
                $page_id = $result['id'];
                //删除page
                $result = $model->where(['id'=>$page_id])->delete();
                if($result===false){
                    $flag=false;
                }else{
                    //删除pageItem
                    $itemModel = new ViewPageItemModel();
                    $result = $itemModel->where(['page_id'=>$page_id])->delete();
                    if($result===false){
                        $flag=false;
                    }
                }
            }
        }
        if($flag){
            $model->commit();
            return $this->apiReturnSuc('删除成功');
        }else{
            $model->rollback();
            $error = $model->getDbError();
            return $this->apiReturnErr($error);
        }
    }

    /**
     * 获取APP页面ids
     */
    public function pageAppQuery(){

        $pages = ['name'=>'首页','page_id'=>1]; //app首页

        $model = $this->model;

        $result = $model->where(['notes'=>'APP分类布局'])->select();

        if($result===false){
            $error = $model->getDbError();
            return $this->apiReturnErr($error);
        }else{
            foreach($result as $val){
                $pages[] = ['name'=>$val['name'],'page_id'=>$val['id']];
            }
            return $this->apiReturnSuc($result);
        }

    }
}
